﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace VSM
{
    public partial class WSCVSM : System.Web.UI.Page
    {
        private int _rowCount = 0;
        private int _checkRow = 0;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (!IsPostBack)
            {
                DateTime firstDate = DateTime.Today.AddDays(1 - DateTime.Today.Day);
                DateTime firstDateNextMonth = firstDate.AddMonths(1);
                DateTime lastDate = firstDateNextMonth.AddDays(-1);

                txtFromDate.Text = firstDate.ToString("dd/MM/yyyy");
                txtToDate.Text = lastDate.ToString("dd/MM/yyyy");
                createStatusDll();
                createStatusDealer();
            }
        }

        private void createStatusDll()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Code");
            dt.Columns.Add("Name");
            dt.Rows.Add("(4,5,6)", "All");
            dt.Rows.Add("(4)", "Waiting");
            dt.Rows.Add("(5)", "Approved");
            dt.Rows.Add("(6)", "Rejected");

            ddlStatus.DataSource = dt;
            ddlStatus.DataTextField = "Name";
            ddlStatus.DataValueField = "Code";
            ddlStatus.DataBind();
        }

        private void createStatusDealer() {
            string sql = "select '-1' CardCode, 'All' CardName ";
            sql +=" union all ";
            sql += " select CardCode, CardName from OCRD where CardType = 'C' and U_WareHouse is not null ";
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0) {
                ddl_Dealer.DataSource = ds.Tables[0];
                ddl_Dealer.DataTextField = "CardName";
                ddl_Dealer.DataValueField = "CardCode";
                ddl_Dealer.DataBind();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            LoadItem();
            foreach (GridViewRow row in grdItem.Rows)
            {
                ViewState["rowindex"] = row.RowIndex;
                CheckBox chkChild = (CheckBox)row.FindControl("chkChild");
                if (chkChild.Checked) chkChild.Checked = false; 
            }
            Timer1.Enabled = false;
        }

       
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdItem_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dt = Session["ItemTable"] as DataTable;
            if (dt != null)
            {
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                this.grdItem.DataSource = Session["ItemTable"];
                this.grdItem.DataBind();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private string GetSortDirection(string column)
        {
            string sortDirection = "ASC";
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdItem_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                if (Session["ChosenItem"] != null)
                {
                    Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                    Label code = (Label)e.Row.FindControl("lblItemCode");
                    try
                    {
                        if (code != null && dicItem[code.Text.Trim()].Length > 0)
                        {
                            CheckBox checkBox = (CheckBox)e.Row.FindControl("chkChild");
                            if (checkBox != null)
                            {
                                checkBox.Checked = true;
                                _checkRow++;
                                if (_checkRow == _rowCount)
                                {
                                    //Check All
                                    GridViewRow headerRow = this.grdItem.HeaderRow;
                                    ((CheckBox)headerRow.FindControl("chkheader")).Checked = true;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //
                    }
                }
            }
        }

        private void LoadItem()
        {
            //try
            //{
            //    MasterData obj = new MasterData();
            //    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            //    DataSet dsOITM = obj.GetItemsByItemGroup(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), hdnItmsGrpCod.Value);

            //    if (dsOITM != null && dsOITM.Tables != null & dsOITM.Tables[0].Rows.Count > 0)
            //    {
            //        BindBP(dsOITM.Tables[0]);
            //    }
            //}
            //catch (Exception ex)
            //{

            //}        
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void BindBP(DataTable tb)
        {
            Session["ItemTable"] = tb;
            this.grdItem.DataSource = tb;
            this.grdItem.DataBind();
        }

        protected void btn_Filter_Click(object sender, EventArgs e)
        {
            LoadDataFilter();
        }

        private void LoadDataFilter() {
            string sql = "select ROW_NUMBER() OVER(ORDER BY gs.GeneralID DESC) AS No, gs.GeneralID, gs.ServiceDate, gs.DealerCode, ";
            sql += " ws.SeqNo, ws.VIN, ws.CustomerName, ws.FailureDate, ws.Model, ws.EngineNumber,  ";
            sql += " ConditionCode, ws.RegistrationNum, gs.Status,  ";
            sql += " case gs.Status when 0 then 'Not Submited' when 1 then 'Pending' when 2 then 'Approved'  ";
            sql += " when 3 then 'Rejected' else '' end StatusName ";
            sql += " from U_GeneralService gs  ";
            sql += " left join U_WSC ws on gs.GeneralID = ws.GeneralID where gs.JobKind = '004' ";
            sql += " AND gs.DealerCode = '" + Session[Utils.AppConstants.ID_Dealer] + "'";
            sql += "AND gs.Status <> 0 ";
            if (ddlStatus.SelectedValue != "-1")
            {
                sql += " AND gs.Status = " + ddlStatus.SelectedValue;
            }
            if(ddl_Dealer.SelectedValue != "-1"){
                sql += " AND gs.DealerCode = '" + ddl_Dealer.SelectedValue + "'";
            }

            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            grdItem.DataSource = ds.Tables[0];
            grdItem.DataBind();
        }



        protected void btn_Approve_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dicItem = new Dictionary<string, string>();
            for (int i = 0; i < this.grdItem.Rows.Count; i++)
            {
                CheckBox checkBox = (CheckBox)this.grdItem.Rows[i].FindControl("chkApprove");

                if (checkBox != null)
                {
                    if (checkBox.Checked)
                    {
                        Label gID = (Label)this.grdItem.Rows[i].FindControl("lbGeneralID");

                        Services sv = new Services();
                        sv.ExecuteQuery("DEALER", "UPDATE U_GeneralService SET Status = 2 WHERE GeneralID = " + gID.Text);
                    }
                }
            }
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Update Complete,');", true);
            LoadDataFilter();
        }

        protected void btn_Reject_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dicItem = new Dictionary<string, string>();
            for (int i = 0; i < this.grdItem.Rows.Count; i++)
            {
                CheckBox checkBox = (CheckBox)this.grdItem.Rows[i].FindControl("chkReject");

                if (checkBox != null)
                {
                    if (checkBox.Checked)
                    {
                        Label gID = (Label)this.grdItem.Rows[i].FindControl("lbGeneralID");

                        Services sv = new Services();
                        sv.ExecuteQuery("DEALER", "UPDATE U_GeneralService SET Status = 3 WHERE GeneralID = " + gID.Text);
                    }
                }
            }
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Update Complete,');", true);
            LoadDataFilter();
        }

    }
}
